<template>
  <div class="create-group-container">
    <!-- 导航栏 -->
    <van-nav-bar class="custom-navbar">
      <template #left>
        <van-icon name="arrow-left" class="nav-icon" @click="backRoute" />
      </template>
      <template #title>
        <span class="nav-title">创建群聊</span>
      </template>
    </van-nav-bar>

    <div class="group-name-section">
      <van-field v-model="groupName" class="group-name-input" placeholder="请输入群聊名称" :border="false">
        <template #left-icon>
          <van-icon name="chat-o" size="18" style="margin-right: 8px;" />
        </template>
      </van-field>
    </div>

    <div class="search-name-section">
      <van-field v-model="searchKeyword" class="group-name-input" placeholder="搜索联系人" :border="false">
        <template #left-icon>
          <van-icon name="search" size="18" style="margin-right: 8px;" />
        </template>
      </van-field>
    </div>

    <!-- 联系人列表 -->
    <div class="contact-list">
      <!-- 全选区域 -->
      <div class="select-all-section">
        <van-checkbox v-model="selectAll" @change="toggleSelectAll">
          全选
        </van-checkbox>
        <div class="selected-count">已选 {{ selectedCount }} 人</div>
      </div>

      <!-- 联系人列表 -->
      <div v-for="contact in filteredContacts" :key="contact.goalId" class="contact-item">
        <van-checkbox v-model="selectedContacts[contact.goalId]" />
        <div class="avatar">
          <img :src="contact.avatar" alt="">
        </div>
        <div class="name">{{ contact.displayName }}</div>
      </div>

      <!-- 空状态 -->
      <div v-if="filteredContacts.length === 0" class="empty-tip">
        未找到匹配的联系人
      </div>
    </div>

    <!-- 完成按钮 -->
    <div class="footer">
      <van-button type="primary" round class="complete-btn" :disabled="selectedCount < 1" @click="createGroup">
        完成 ({{ selectedCount }})
      </van-button>
    </div>
  </div>
</template>

<script>
import { postAction, getFileAccessHttpUrl } from '@/api'

export default {
  name: "CreateGroup",
  data() {
    return {
      searchKeyword: "",
      groupName: "",
      contacts: [],
      selectedContacts: {}, // 存储选中状态 {contactId: boolean}
      selectAll: false,
      userId: this.$store.getters.userid,
    }
  },
  computed: {
    // 过滤后的联系人列表
    filteredContacts() {
      if (!this.searchKeyword) return this.contacts;
      const keyword = this.searchKeyword.toLowerCase();
      return this.contacts.filter(contact =>
        contact.displayName.toLowerCase().includes(keyword)
      )
    },
    // 已选中的联系人数量
    selectedCount() {
      return Object.values(this.selectedContacts).filter(selected => selected).length;
    }
  },
  created() {
    console.log('用户头像:', this.$store.getters.avatar)
    this.initContactsList();
  },
  methods: {
    backRoute() {
      this.$router.push({ name: 'chat' })
    },

    // 初始化联系人列表
    initContactsList() {
      postAction('/sys/chat/relative', {
        userId: this.userId
      }).then((res) => {
        if (res.success) {
          this.processContacts(res.result);
          console.log("🚀 ~ :132 ~ initContactsList ~ this.selectedContacts:", this.selectedContacts)
        } else {
          console.error('加载联系人失败:', res.message);
          this.$toast('加载联系人失败');
        }
      }).catch((err) => {
        console.error('加载联系人异常:', err);
        this.$toast('加载联系人异常');
      });
    },

    // 处理联系人数据
    processContacts(list) {
      // 只保留个人联系人（过滤掉群聊）
      this.contacts = list.filter(contact => contact.is_group == 0)
        .map(contact => {
          contact.avatar = contact.avatar
            ? getFileAccessHttpUrl(contact.avatar)
            : '/static/mobile/img/common/user_default.webp';
          // 初始化选中状态为false
          this.$set(this.selectedContacts, contact.goalId, false);
          return contact;
        });
    },

    // 全选/取消全选
    toggleSelectAll(checked) {
      console.log("🚀 ~ :158 ~ toggleSelectAll ~ checked:", checked)
      // 只对当前显示的联系人进行操作
      this.filteredContacts.forEach(contact => {
        this.selectedContacts[contact.goalId] = checked;
      });
    },

    // // 更新全选状态
    // updateSelectAllState() {
    //   // 检查当前显示的联系人是否全部被选中
    //   this.selectAll = this.filteredContacts.length > 0 &&
    //     this.filteredContacts.every(contact => this.selectedContacts[contact.goalId]);
    // },

    // 创建群聊
    createGroup() {
      console.log("🚀 ~ :189 ~ createGroup ~ this.selectedContacts:", this.selectedContacts)
      if (!this.groupName.trim()) {
        this.$toast('请输入群聊名称');
        return;
      }
      if (this.groupName.includes(" ")) {
        this.$toast('群聊名称不能包含空格');
        return;
      }
      if (!this.groupName.length > 20) {
        this.$toast('群聊名称过长');
        return;
      }
      // 获取选中的联系人ID
      const selectedIds = Object.keys(this.selectedContacts)
        .filter(goalId => this.selectedContacts[goalId]);

      if (selectedIds.length < 1) {
        this.$toast('请至少选择一名联系人');
        return;
      }

      // 显示加载状态
      this.$toast.loading({
        message: '创建中...',
        forbidClick: true,
        duration: 0
      });

      postAction("/sys/chat/group/createGroup", {
        groupName: this.groupName,
        memberIds: JSON.stringify(Object.keys(this.selectedContacts).filter(goalId => this.selectedContacts[goalId] === true))
      }).then(res => {
        this.$toast.clear();
        if (res.success) {
          this.$toast.success('群聊创建成功');
          // 创建成功后返回上一页
          setTimeout(() => {
            this.$router.go(-1);
          }, 1500);
        } else {
          this.$toast.fail(res.message || '创建群聊失败');
        }
      }).catch(err => {
        this.$toast.clear();
        this.$toast.fail('创建群聊异常');
        console.error('创建群聊异常:', err);
      });
    }
  }
}
</script>

<style scoped>
.create-group-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;
  overflow: hidden;
}

.custom-navbar {
  background-color: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.nav-title {
  font-size: 16px;
  font-weight: bold;
  color: #26B1A1;
  letter-spacing: 0.5px;
}

.van-nav-bar .van-icon {
  color: #26B1A1;
  font-size: 16px;
}



/* 群聊名称区域 - 与搜索区域统一样式 */
.group-name-section {
  padding: 12px 16px;
  background-color: #fff;
}

.search-name-section {
  padding: 0px 16px;
  background-color: #fff;
}

.group-name-input {
  background-color: #f7f8fa;
  border-radius: 8px;
  padding: 12px 16px;
}

.search-name-input {
  background-color: #f7f8fa;
  border-radius: 8px;
}




/* 全选区域 */
.select-all-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 16px;
  background-color: #fff;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 10;
}

.selected-count {
  font-size: 14px;
  color: #666;
}

/* 联系人列表 */
.contact-list {
  flex: 1;
  overflow-y: auto;
  background-color: #fff;
}

.contact-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f8f8f8;
}

.contact-item .van-checkbox {
  margin-right: 12px;
}

.avatar {
  width: 44px;
  height: 44px;
  border-radius: 20%;
  overflow: hidden;
  margin-right: 18px;
  background-color: #f0f0f0;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  flex: 1;
}

/* 空状态提示 */
.empty-tip {
  text-align: center;
  padding: 40px 0;
  color: #999;
  font-size: 14px;
}

/* 完成按钮 */
.footer {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 100;
}

.complete-btn {
  width: 120px;
  height: 44px;
  font-size: 16px;
  font-weight: 500;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  background: linear-gradient(90deg, #26B1A1, #6FD0B3);
}

.complete-btn:disabled {
  background: #c8c9cc;
  border-color: #c8c9cc;
  opacity: 0.8;
}
</style>
